// @ts-check
import axios from 'axios'
import io from 'socket.io-client'
import getSocketURI from './getSocketURI'

const debug = process.env.NODE_ENV !== 'production'

let socketInstance
const USE_SERVER = false

const createSocket = async () => {
  if (!USE_SERVER) return Promise.reject(null)
  return axios.get(getSocketURI())
    .then(() => {
      if (!socketInstance) {
        return new Promise(resolve => {
          socketInstance = io(getSocketURI())
          socketInstance.on('connect', () => {
            if (debug) {
              console.log('socket connected')
            }
            resolve(socketInstance)
          })
          socketInstance.on('disconnect', () => {
            if (debug) {
              console.log('socket disconnected')
            }
          })
        })
      }
      return socketInstance
    })
}

export default createSocket
